﻿/// <reference path="../../../../_3rd part/SharePoint.d.ts"/>
var spdevlab;
(function (spdevlab) {
    (function (fields) {
        var AutoUploadImageField = (function () {
            function AutoUploadImageField(fieldName) {
                this._selectedImageUrl = "";
                this._imageUploadFileControlId = "";
                this._imagePreviewControlId = "";
                this._imageFileUploadUrlControlId = "";
                this._fieldName = fieldName;

                this._imageUploadFileControlId = "spdevlab_imageFileUploadControl_" + this._fieldName;
                this._imagePreviewControlId = "spdevlab_imagePreviewControl_" + this._fieldName;
                this._imageFileUploadUrlControlId = "spdevlab_imageUrlControl_" + this._fieldName;

                spdevlab.fields.AutoUploadImageField._instances[this._fieldName] = this;
            }
            AutoUploadImageField.onFileControlChanged = function (instanceId) {
                var currentInstance = spdevlab.fields.AutoUploadImageField._instances[instanceId];

                if (currentInstance) {
                    currentInstance._uploadFile();
                } else {
                    alert('Err: [Cannot find instance with id:[' + instanceId + ']');
                }
            };

            AutoUploadImageField.prototype._uploadFile = function () {
                var _this = this;
                var imageSourceControl = document.getElementById(this._imageUploadFileControlId);

                if (imageSourceControl.files.length === 0) {
                    return;
                }

                // TODO
                var parts = imageSourceControl.value.split("\\");

                var filename = parts[parts.length - 1];
                var fileTimestamp = new Date().getTime();

                // add timestamp
                var filenameParts = filename.split(".");

                if (filenameParts.length > 1) {
                    var fileExtension = filenameParts.pop();
                    filenameParts.push(fileTimestamp);
                    filenameParts.push(fileExtension);
                } else {
                    filenameParts.push(fileTimestamp);
                }

                filename = filenameParts.join(".");

                var file = imageSourceControl.files[0];

                var reader = new FileReader();

                var waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Image is being uploaded...', 'Please wait while your image is being uploaded...', 200, 450);

                reader.onload = function (ev) {
                    var buffer = ev.target.result;

                    var bytes = new Uint8Array(buffer);
                    var content = new SP.Base64EncodedByteArray();

                    for (var b = 0; b < bytes.length; b++)
                        content.append(bytes[b]);

                    // TODO
                    var serverRelativeUrl = _spPageContextInfo.siteServerRelativeUrl + "/SiteCollectionImages";
                    var ctx = SP.ClientContext.get_current();

                    var createInfo = new SP.FileCreationInformation();

                    createInfo.set_content(content);
                    createInfo.set_overwrite(true);
                    createInfo.set_url(filename);

                    var files = ctx.get_site().get_rootWeb().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();
                    ctx.load(files);

                    files.add(createInfo);

                    ctx.executeQueryAsync(function () {
                        // TODO
                        var t = window.setInterval(function () {
                            var fileLink = serverRelativeUrl + "/" + filename;

                            document.getElementById(_this._imageFileUploadUrlControlId).innerHTML = "<a target='_blank' href='" + fileLink + "' >" + fileLink + "</a>";

                            window.clearInterval(t);

                            var filePreview = document.getElementById(_this._imagePreviewControlId);

                            filePreview.style.display = '';
                            filePreview.src = fileLink + "?height=100";

                            _this._selectedImageUrl = fileLink + ", " + filename;
                            waitDialog.close();
                        }, 2500);
                    }, function (sender, args) {
                        waitDialog.close();
                        alert("Error while uploading image... " + args.get_message());
                    });
                };

                reader.readAsArrayBuffer(file);
            };

            AutoUploadImageField.prototype._viewTemplate = function (renderCtx, field, listItem, listSchema) {
                // TODO
                var currentVal = '(null)';

                if (renderCtx != null && renderCtx.CurrentItem != null)
                    currentVal = eval('renderCtx.CurrentItem.' + field.Name);

                var parts = currentVal.toString().split(',');

                var url = parts[0];
                var description = parts[1];

                var result = "";

                if (url !== '' && url !== null)
                    result += "<div><img width='96' height='96' src='" + url + "?width=96&height=96" + "' id='" + this._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;margin-top:10px'></img></div>";
else
                    result += "<div><img width='96' height='96' src='' id='" + this._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;display:none; margin-top:10px'></img></div>";

                return result;
            };

            AutoUploadImageField.prototype._displayFormTemplate = function (ctx) {
                var _this = this;
                if (ctx == null || ctx.CurrentFieldValue == null)
                    return '';

                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

                if (formCtx == null || formCtx.fieldSchema == null)
                    return '';

                formCtx.registerGetValueCallback(formCtx.fieldName, function () {
                    return _this._selectedImageUrl;
                });

                var parts = ctx.CurrentFieldValue.toString().split(',');

                var url = parts[0];
                var description = parts[1];

                var result = "";

                if (url !== '' && url !== null)
                    result += "<div><img width='96' height='96' src='" + url + "?width=96&height=96" + "' id='" + this._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;margin-top:10px'></img></div>";
else
                    result += "<div><img width='96' height='96' src='' id='" + this._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;display:none; margin-top:10px'></img></div>";

                return result;
            };

            AutoUploadImageField.prototype._newFormTemplate = function (ctx) {
                var _this = this;
                if (ctx == null || ctx.CurrentFieldValue == null)
                    return '';

                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

                if (formCtx == null || formCtx.fieldSchema == null)
                    return '';

                formCtx.registerGetValueCallback(formCtx.fieldName, function () {
                    return _this._selectedImageUrl;
                });

                var parts = ctx.CurrentFieldValue.toString().split(',');

                var url = parts[0];
                var description = parts[1];

                // TODO
                var result = "";

                result += "<div id='uploadFileExperience' style='padding:10px; border:1px #dedede solid'>";
                result += "Select image file: <input onchange=\"javascript:spdevlab.fields.AutoUploadImageField.onFileControlChanged('" + this._fieldName + "');\" type='file' id='" + this._imageUploadFileControlId + "'><br/>";

                if (url !== '' && url !== null)
                    result += "<div><img width='96' height='96' src='" + url + "?width=96&height=96" + "' id='" + this._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;margin-top:10px'></img></div>";
else
                    result += "<div><img width='96' height='96' src='' id='" + this._imagePreviewControlId + "' style='border:2px #dedede solid; padding:5px;display:none; margin-top:10px'></img></div>";

                var imageLink = "<a target='_blank' href='" + url + "' >" + url + "</a>";

                result += "<div id='" + this._imageFileUploadUrlControlId + "'>" + imageLink + "</div>";
                result += "</div>";

                this._selectedImageUrl = url + ", " + description;

                return result;
            };

            AutoUploadImageField.prototype.Init = function () {
                var _this = this;
                var fieldName = this._fieldName;
                var visaFieldTemplates = {
                    Templates: {
                        Fields: {}
                    }
                };

                visaFieldTemplates.Templates.Fields[fieldName] = {};

                visaFieldTemplates.Templates.Fields[fieldName]["View"] = function (renderCtx, field, listItem, listSchema) {
                    return _this._viewTemplate(renderCtx, field, listItem, listSchema);
                };
                visaFieldTemplates.Templates.Fields[fieldName]["NewForm"] = function (renderCtx) {
                    return _this._newFormTemplate(renderCtx);
                };
                visaFieldTemplates.Templates.Fields[fieldName]["EditForm"] = function (renderCtx) {
                    return _this._newFormTemplate(renderCtx);
                };
                visaFieldTemplates.Templates.Fields[fieldName]["DisplayForm"] = function (renderCtx) {
                    return _this._displayFormTemplate(renderCtx);
                };

                SPClientTemplates.TemplateManager.RegisterTemplateOverrides(visaFieldTemplates);
            };
            AutoUploadImageField._instances = [];
            return AutoUploadImageField;
        })();
        fields.AutoUploadImageField = AutoUploadImageField;
    })(spdevlab.fields || (spdevlab.fields = {}));
    var fields = spdevlab.fields;
})(spdevlab || (spdevlab = {}));

(function () {
    var field = new spdevlab.fields.AutoUploadImageField("AutoUploadImageField");
    field.Init();
})();
